﻿using System;
using System.Threading.Tasks;
using Plugins.FormicArch.Core.AssetsCenter;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace FormicArch.Core.AssetsCenter
{
    public class AssetLoaderHelper:IAssetLoaderHelper
    {
        public T LoadAsset<T>(string assetName)
        {
            return Addressables.LoadAssetAsync<T>(assetName).Task.Result;
        }
        
        public async Task<T> LoadAssetAsync<T>(string assetName)
        {
            return await Addressables.LoadAssetAsync<T>(assetName).Task;
        }

        public void LoadAssetAsync<T>(string assetName, Action<T> callback)
        {
            Addressables.LoadAssetAsync<T>(assetName).Completed += operation =>
            {
                if (operation.Status != AsyncOperationStatus.Succeeded)
                {
                    Debug.LogError("Failed to load asset: " + operation.DebugName);
                }
                callback?.Invoke(operation.Result);
            };
        }

        public GameObject Instantiate(string assetName)
        {
            return Addressables.InstantiateAsync(assetName).Task.Result;
        }
        

        public async Task<GameObject> InstantiateAsync(string assetName)
        {
            return await Addressables.InstantiateAsync(assetName).Task;
        }

        public void InstantiateAsync(string assetName, Action<GameObject> callback)
        {
             Addressables.InstantiateAsync(assetName).Completed += operation =>
            {
                if (operation.Status != AsyncOperationStatus.Succeeded)
                {
                    Debug.LogError("Failed to load asset: " + operation.DebugName);
                }
                callback?.Invoke(operation.Result);
            };
        }

        public bool ReleaseInstance(GameObject obj)
        {
            return Addressables.ReleaseInstance(obj);
        }
    }
}